package com.azt.back.action;

import com.xiaoleilu.hutool.convert.Convert;
import com.xiaoleilu.hutool.util.StrUtil;
import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Action基类
 * Created by shangwq on 2016/11/17.
 */
public abstract class BaseAction {

    protected Logger LOGGER = Logger.getLogger(this.getClass());

    @Autowired
    protected HttpServletRequest request;

    @Autowired
    protected HttpServletResponse response;

    protected void setAttr(String name, Object value) {
        request.setAttribute(name, value);
    }

    protected String getPara(String name) {
        return request.getParameter(name);
    }

    protected String getParaTrim(String name) {
        return StrUtil.trim(getPara(name));
    }

    protected Integer getParaToInt(String name) {
        return Convert.toInt(getPara(name));
    }

    protected Integer getParaToInt(String name, Integer defaultValue) {
        return Convert.toInt(getPara(name), defaultValue);
    }

    protected Double getParaToDouble(String name) {
        return Convert.toDouble(getPara(name));
    }

    protected Double getParaToDouble(String name, Double defaultValue) {
        return Convert.toDouble(getPara(name), defaultValue);
    }

    /**
     * 安全转化Date，默认格式为yyyy-MM-dd
     * */
    protected Date getParaToDate(String name) {
        return getParaToDate(name, "yyyy-MM-dd", null);
    }

    protected Date getParaToDate(String name, String format) {
        return getParaToDate(name, format, null);
    }

    protected Date getParaToDate(String name, String format, Date defaultValue) {
        String value = getPara(name);
        Date date = defaultValue;
        try {
            date = new SimpleDateFormat(format).parse(Convert.toStr(value));
        } catch (Exception e) {}
        return date;
    }

    /**
     * 转换为boolean String支持的值为：true、false、yes、ok、no，1,0 如果给定的值为空，或者转换失败，返回默认值 转换失败不会报错
     * */
    protected Boolean getParaToBool(String name) {
        return Convert.toBool(getPara(name));
    }

    /**
     * 转换为boolean String支持的值为：true、false、yes、ok、no，1,0 如果给定的值为空，或者转换失败，返回默认值 转换失败不会报错
     * */
    protected Boolean getParaToBool(String name, Boolean defaultValue) {
        return Convert.toBool(getPara(name), defaultValue);
    }

    protected void addCookie(Cookie cookie) {
        response.addCookie(cookie);
    }

    /**
     * 发送文本。使用UTF-8编码。
     */
    protected void renderText(String text) {
        render("text/plain;charset=UTF-8", text);
    }

    /**
     * 发送json。使用UTF-8编码。
     */
    protected void renderJson(String text) {
        render("application/json;charset=UTF-8", text);
    }

    /**
     * 发送xml。使用UTF-8编码。
     */
    protected void renderXml(String text) {
        render("text/xml;charset=UTF-8", text);
    }

    /**
     * 发送内容。使用UTF-8编码。
     */
    protected void render(String contentType, String text) {
        response.setContentType(contentType);
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        PrintWriter writer = null;
        try {
            writer = response.getWriter();
            writer.write(text);
            writer.flush();
        } catch (IOException e) {
            LOGGER.error("render error", e);
        } finally {
            IOUtils.closeQuietly(writer);
        }
    }

    protected String getIp() {
        String ip = request.getHeader("x-forwarded-for");
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
            ip = request.getHeader("Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
            ip = request.getRemoteAddr();
        }
        return ip.equals("0:0:0:0:0:0:0:1")?"127.0.0.1":ip;
    }

    /**
     * 判断是否是ajax请求
     */
    protected boolean isAjax() {
        String header = request.getHeader("X-Requested-With");
        return "XMLHttpRequest".equalsIgnoreCase(header);
    }
}
